import { Router2, first } from "../addons/router";
import {
  getConfig,
  getConfigLock,
  putConfig,
  putConfigLock,
} from "../models/config";
import { withAuth, withRoot, withRootW } from "../services/sercurity";
import { getSlaveConfig } from "../services/slave";
import { applyPatch, JsonPatchError } from "fast-json-patch";
import { StatusError, json, withContent, withParams } from "itty-router";

const router = Router2({ base: "/config" });
export default { base: "/config/*", handle: router.handle };

router.all("*", withParams, withContent);

router.get("/lock", withRoot, async (_, { kv }) => {
  return json(await getConfigLock(kv));
});

router.put("/lock", withRoot, async ({ content }, { kv }) => {
  return json(await putConfigLock(kv, content));
});

router.get("/", withAuth, async ({ query }, { kv }) => {
  query.host = first(query.host);
  if (query.host !== undefined) {
    return json((await getSlaveConfig(kv, query.host))!);
  } else {
    return json(await getConfig(kv));
  }
});

router.patch("/", withRootW, async ({ content }, { kv }) => {
  try {
    const { newDocument } = applyPatch(await getConfig(kv), content);
    await putConfig(kv, newDocument);
    return json(null);
  } catch (reason) {
    if (!(reason instanceof JsonPatchError)) {
      throw reason;
    }
    throw new StatusError(400, `应用补丁失败：${reason.message}`);
  }
});
